<template>
	<van-nav-bar
		title="编辑收货地址"
		left-text=""
		left-arrow
		@click-left="goBack"
	/>
	<van-address-edit
		:area-list="areaList"
		show-set-default
		:address-info="addressInfo"
		:area-columns-placeholder="['请选择', '请选择', '请选择']"
		show-delete
		@save="onSave"
		@delete="onDelete"
	/>
</template>
<script setup>
	import { areaList } from "@vant/area-data";
	const route = useRoute();
	const router = useRouter();
	let addressInfo = reactive({
		id: "",
		name: "",
		tel: "",
		addressDetail: "",
		areaCode: "",
		isDefault: false,
	});
	const goBack = () => {
		router.push("/business/address/index");
	};
	const { cookies } = useCookies();

	const LoginUser = reactive(cookies.get("LoginUser"));
	const onSave = async (val) => {
		let data = {
			consignee: val.name,
			code: val.areaCode,
			address: val.addressDetail,
			mobile: val.tel,
			status: val.isDefault == true ? "1" : "0",
			busid: LoginUser.id,
			id: addressInfo.id,
		};
		let result = await Api.business.addressEdit(data);
		if (result.code == 1) {
			showSuccessToast({
				message: result.msg,
				onClose: function () {
					router.push("/business/address/index");
				},
			});
		} else {
			showFailToast(result.msg);
		}
	};
	onBeforeMount(() => {
		if (route.query.id) {
			getAddressById(route.query.id);
		}
	});
	// 获取地址信息
	const getAddressById = async (id) => {
		const result = await Api.business.getAddressById({ id: id });
		if (result.code == 1) {
			let data = result.data;
			addressInfo.id = data.id;
			addressInfo.name = data.consignee;
			addressInfo.tel = data.mobile;
			addressInfo.addressDetail = data.address;
			addressInfo.areaCode = data.district ?? data.city ?? data.province;
			addressInfo.isDefault = data.status == 1 ? true : false;
		}
	};
	// 删除地址信息
	const onDelete = () => {
		showConfirmDialog({
			title: "删除",
			message:
				"确定删除收货地址吗？	",
		})
		.then(async () => {
			let data = {
				id: addressInfo.id,
			};
			let result = await Api.business.addressDel(data);
			if (result.code == 1) {
				showSuccessToast({
					message: result.msg,
					onClose: function () {
						router.push("/business/address/index");
					},
				});
			} else {
				showFailToast(result.msg);
			}
		})
		.catch(() => {});
	};
</script>